# -*- coding: utf-8 -*-
# TencentBlueKing is pleased to support the open source community by making
# 蓝鲸智云 - PaaS 平台 (BlueKing - PaaS System) available.
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
#     http://opensource.org/licenses/MIT
#
# Unless required by applicable law or agreed to in writing, software distributed under
# the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions and
# limitations under the License.
#
# We undertake not to change the open source license (MIT license) applicable
# to the current version of the project delivered to anyone in the future.

# Generated by Django 3.2.12 on 2023-05-30 08:13
from django.db import migrations
from django.db.models import Count


def initial_bp_generation(apps, schema_editor):
    """补全 BuildProcess.generation 字段"""
    if schema_editor.connection.alias != "workloads":
        return

    alias = schema_editor.connection.alias
    BuildProcess = apps.get_model("api", "BuildProcess")
    app_ids = (
        BuildProcess.objects.using(alias)
        # 调用空参数的 order_by() 清除默认的排序规则, 否则会导致 group by app_id, created
        .order_by()
        # initial_bp_generation 支持重入(只更新 generation=0) 的 BuildProcess
        .filter(generation=0)
        .values_list("app_id", flat=True)
        .annotate(count=Count("app_id"))
    )
    for app_id in app_ids:
        to_update = []
        bps = BuildProcess.objects.using(alias).filter(generation=0, app_id=app_id).order_by("-created")
        for idx, bp in enumerate(bps, start=1):
            bp.generation = idx
            to_update.append(bp)
        BuildProcess.objects.using(alias).bulk_update(to_update, ["generation"])


class Migration(migrations.Migration):

    dependencies = [
        ('api', '0013_auto_20230629_1229'),
    ]
    # 由于 BuildProcess 数据量较大, 关闭事务避免锁表
    # initial_bp_generation 支持重入(只更新 generation=0) 的 BuildProcess
    atomic = False

    operations = [migrations.RunPython(initial_bp_generation)]
